package main

import (
	"JudgeSandBox/common"
	"JudgeSandBox/judge"
	"JudgeSandBox/utils"
	"encoding/json"
	"os"
)

func Exec() error {
	acceptJudgeRequest := make([]byte, 1024*1024)
	dataLen, _ := os.Stdin.Read(acceptJudgeRequest)
	utils.PrintToLog("exec层接收请求：", string(acceptJudgeRequest[:dataLen]))
	request := common.JudgeRequest{}
	if err := json.Unmarshal(acceptJudgeRequest[:dataLen], &request); err != nil {
		utils.PrintToLog(err)
	}

	//开始测评
	response := common.JudgeResponse{
		Uuid:     request.Uuid,
		Lang:     request.Lang,
		UseCases: request.UseCases,
		Answers:  request.Answers,
	}

	var judgeImpl judge.Judge = judge.GetJudgeImpl(request.Lang)

	if err := judgeImpl.NewWorkSpace(request); err != nil {
		response.ResultType = common.CompileError
		response.ErrorMessage = err.Error()
		if marshal, err := json.Marshal(response); err == nil {
			utils.PrintToLog("NewWorkSpace", "marshal", string(marshal))
			os.Stdout.Write(marshal)
		}
		os.Stdout.Close()
		utils.PrintToLog("NewWorkSpace", "Done")
		judgeImpl.Done(request)
		utils.PrintToLog(err)
		return err
	}

	if err := judgeImpl.Compile(request); err != nil {
		response.ResultType = common.CompileError
		response.ErrorMessage = err.Error()
		if marshal, err := json.Marshal(response); err == nil {
			utils.PrintToLog("Compile", "marshal", string(marshal))
			os.Stdout.Write(marshal)
		}
		os.Stdout.Close()
		utils.PrintToLog("Compile", "Done")
		judgeImpl.Done(request)
		utils.PrintToLog(err)
		return err
	}

	if mresponse, err := judgeImpl.Execute(request); err == nil {
		if mresponse != nil {
			marshal, _ := json.Marshal(mresponse)
			utils.PrintToLog("Execute", "marshal", string(marshal))
			os.Stdout.WriteString(string(marshal))
		}
	} else {
		utils.PrintToLog("execute", err)
	}
	utils.PrintToLog("Execute", "Done")
	judgeImpl.Done(request)
	return nil
}
